package com.qingyun.customview.draw.demo

import android.R
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Shader
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

class MyTextView2 @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = R.attr.textViewStyle,
) : AppCompatTextView(context, attrs, defStyleAttr) {

    private var mViewWidth = 0
    private lateinit var mPaint: Paint
    private var mLinearGradient: LinearGradient? = null
    private var mGradientMatrix: Matrix? = null

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        if (mViewWidth == 0) {
            mViewWidth = measuredWidth
            if (mViewWidth > 0) {
                mPaint = paint
                mLinearGradient = LinearGradient(
                    0f,
                    0f,
                    mViewWidth.toFloat(),
                    0f,
                    intArrayOf(
                        Color.RED,
                        Color.YELLOW,
                        Color.GREEN,
                        Color.CYAN,
                        0xffffff,
                        Color.BLUE
                    ),
                    null,
                    Shader.TileMode.CLAMP
                )
                mPaint.setShader(mLinearGradient)
                mGradientMatrix = Matrix()
            }
        }
    }

    private var mTranslate: Float = 0f
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (mGradientMatrix != null) {
            mTranslate += mViewWidth / 5
            if (mTranslate > 2 * mViewWidth) {
                mTranslate = -mViewWidth.toFloat()
            }
            mGradientMatrix!!.setTranslate(mTranslate, 0f)
            mLinearGradient?.setLocalMatrix(mGradientMatrix)
            postInvalidateDelayed(100)
        }
    }
}